const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const koaBodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const cors = require("koa2-cors");
const koaBody = require("koa-body");
const compress = require("koa-compress"); //压缩数据

const index = require("./routes/index");
const login = require("./routes/login");
const profile = require("./routes/profile");
const home = require("./routes/home");
const mail = require("./routes/mail");

// error handler
onerror(app);

// middlewares
app.use(
  koaBodyparser({
    enableTypes: ["json", "form", "text"],
    // 重新设置参数大小
    jsonLimit: "50mb", // 控制body的parse转换大小 default 1mb
    formLimit: "50mb", //  控制你post的大小  default 56kb
  })
);
app.use(json());
app.use(logger());
app.use(require("koa-static")(__dirname + "/public"));

app.use(
  views(__dirname + "/views", {
    extension: "pug",
  })
);

app.use(
  compress({
    filter: function (content_type) {
      // 只有在请求的content-type中有gzip类型，我们才会考虑压缩，因为zlib是压缩成gzip类型的
      return /jpg|jpeg|png|gif/i.test(content_type);
    },
    threshold: 1024 * 1024, // 阀值，当数据超过1kb的时候，可以压缩
    flush: require("zlib").Z_SYNC_FLUSH, // zlib是node的压缩模块
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(cors());
app.use(index.routes(), index.allowedMethods());
app.use(login.routes(), login.allowedMethods());
app.use(profile.routes(), profile.allowedMethods());
app.use(home.routes(), home.allowedMethods());
app.use(mail.routes(), mail.allowedMethods());

app.listen(8080, () => {
  console.log("server has started listening at port 8080!");
});
// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});
module.exports = app;
